package app.controller.city;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import common.standard.table.FaultNumFieldEnum;
import refactor.entity.AccessControl;
import common.standard.table.AccessControlFieldEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.zhou.ExcelExportor;
import com.zhou.annotation.CellName;

import app.entity.Pager;
import app.entity.UserSession;
import app.service.DeviceManageService;
import app.utils.Common;
import app.utils.DataResponse;
import app.utils.TimeUtils;
import refactor.entity.FaultNum;
import refactor.service.IAccessControlService;
import refactor.service.IFaultNumService;
import siotwx.entity.Devlogs;

/**
 * 这个类用于存放跟设备有关的操作的链接的映射
 * @author 昊琦
 *
 */
@Controller
public class DeviceController {

	@Autowired
	@Qualifier("DeviceManageService")
	private DeviceManageService dms;

	private IAccessControlService accessControlService;

	@Autowired
	public void setAccessControlService(IAccessControlService accessControlService) {
		this.accessControlService = accessControlService;
	}

	private IFaultNumService faultNumService;

	@Autowired
	public void setFaultNumService(IFaultNumService faultNumService) {
		this.faultNumService = faultNumService;
	}

	/**
	 * 异步获取该用户登录地区的所有设备的硬件故障数量
	 * @author 昊琦
	 * @param response
	 * @param session
	 * 创建时间：2018年3月14日18:01:31
	 */
	@PostMapping(value="/ajaxfaultnum")
	public void countFaultNum(HttpServletResponse response,HttpSession session){
	
		
		//查询session中该用户的地区
		UserSession user = (UserSession)session.getAttribute(Common.sessionUser);
		
		Map<String, String>  faultNum = new HashMap<>();
		faultNum.put("faultNum", "0");
		if (user!=null) {
			int regionId = user.getRegionId();
			int num = faultNumService.count(new QueryWrapper<FaultNum>().eq(FaultNumFieldEnum.REGIONID.getFieldName(), regionId));
			faultNum.put("faultNum", String.valueOf(num));
		}
		DataResponse.jsonResponse(response, faultNum);
		
	}
	
	@RequestMapping(value="/dev/{code}/log/days/{days}/page/{page}",method=RequestMethod.GET)
	public void devLogs(@PathVariable("code")String code,@PathVariable("page") Integer page ,@PathVariable("days")Integer days,HttpSession session,HttpServletResponse response){
		UserSession user = (UserSession) session.getAttribute(Common.sessionUser);
		//根据days确定需要查询从哪一天开始的数据
		long timeLongNow = System.currentTimeMillis();
		long timeLongDays = timeLongNow - (days*24*3600*1000L);
		String timeStrDays = TimeUtils.formatTime(timeLongDays, "yyyy-MM-dd");
		timeStrDays+=" 00:00";
		Integer region=user==null?1:user.getRegionId();
		
		Pager pager = new Pager(dms.countDevlogs(region, code, timeStrDays), page, 8);
		List<Devlogs> devlogs =
				dms.getListDevlogs(region, code, timeStrDays,pager );
		bean dataBean = new bean();
		dataBean.setList(devlogs);
		dataBean.setDevlogsPageNo(page);
		dataBean.setDevlogsPageSize(8);
		dataBean.setResultCount(pager.getItemtotal());
		dataBean.setPageCount(pager.getPagetotal());
		DataResponse.jsonResponse(response, dataBean);
	}
	
	
	@RequestMapping(value="/dev/{code}/log/days/{days}/excel",method=RequestMethod.GET)
	public void devLogsExcel(@PathVariable("code")String code,@PathVariable("days")Integer days,HttpSession session,HttpServletResponse response) throws IllegalArgumentException, IllegalAccessException, IOException{
		UserSession user = (UserSession) session.getAttribute(Common.sessionUser);
		//根据days确定需要查询从哪一天开始的数据
		long timeLongNow = System.currentTimeMillis();
		long timeLongDays = timeLongNow - (days*24*3600*1000L);
		String timeStrDays = TimeUtils.formatTime(timeLongDays, "yyyy-MM-dd");
		timeStrDays+=" 00:00";
		Integer region=user==null?1:user.getRegionId();
		
		List<Devlogs> devlogs =
				dms.getListDevlogs(region, code, timeStrDays,null );
		List<excelData> excel=new ArrayList<>();
		for(Devlogs devlog:devlogs){
			excel.add(new excelData(devlog.getFacDesc(),
					devlog.getDevCode(), 
					!"".equals(devlog.getDevStu())?"无":"暂空".equals(devlog.getWorker())?"钥匙开锁":devlog.getWorker(), 
					"".equals(devlog.getPhonenumber())?"---":devlog.getPhonenumber(),
					devlog.getDevStu().equals("1")?"上线":devlog.getDevStu().equals("0")?"掉线":"---", 
					devlog.getDoorStu().equals("1")?"关门":devlog.getDoorStu().equals("0")?"开门":"---", 
					devlog.getEventDate(),
					devlog.getTasktype()));
		}
		
		DataResponse.StreamResponse(response, new ExcelExportor().getExcel(excel),new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date())+".xls");
	}
	
	public class excelData{
		@CellName(name="设施描述")
		private String facDec;
		@CellName(name="设备编码")
		private String devCode;
		@CellName(name="设备类型")
		private String type;
		@CellName(name="操作人")
		private String worker;
		@CellName(name="电话")
		private String tel;
		@CellName(name="状态1")
		private String sta1;
		@CellName(name="状态2")
		private String sta2;
		@CellName(name="时间")
		private String date;
		
		public excelData(String facDec, String devCode, String worker, String tel, String sta1, String sta2,
				String date,String type) {
			this.facDec = facDec;
			this.devCode = devCode;
			this.worker = worker;
			this.tel = tel;
			this.sta1 = sta1;
			this.sta2 = sta2;
			this.date = date;
			this.type=type;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		}
		public String getFacDec() {
			return facDec;
		}
		public void setFacDec(String facDec) {
			this.facDec = facDec;
		}
		public String getDevCode() {
			return devCode;
		}
		public void setDevCode(String devCode) {
			this.devCode = devCode;
		}
		public String getWorker() {
			return worker;
		}
		public void setWorker(String worker) {
			this.worker = worker;
		}
		public String getTel() {
			return tel;
		}
		public void setTel(String tel) {
			this.tel = tel;
		}
		public String getSta1() {
			return sta1;
		}
		public void setSta1(String sta1) {
			this.sta1 = sta1;
		}
		public String getSta2() {
			return sta2;
		}
		public void setSta2(String sta2) {
			this.sta2 = sta2;
		}
		public String getDate() {
			return date;
		}
		public void setDate(String date) {
			this.date = date;
		}
		
		
	}

	/**
	 * 对某个设备添加临时开门人。如果添加的是已存在的开门人，则更新授权时间
	 *
	 * @param deviceId 设备id
	 * @param userId 用户id
	 * @param time 过期时间
	 * @param response response响应
	 */
	@RequestMapping(value="/device/{devid}/user/{user}/timelimit/{time}")
	public void addOperator(@PathVariable("devid") Integer deviceId,
							@PathVariable("user") Integer userId,
							@PathVariable("time") String time,
							HttpServletResponse response) {

		QueryWrapper<AccessControl> accessControlQueryWrapper = new QueryWrapper<AccessControl>().eq(AccessControlFieldEnum.USER_ID.getFieldName(), userId)
				.eq(AccessControlFieldEnum.DEVICE_ID.getFieldName(), deviceId);

		AccessControl accessControlServiceOne = accessControlService.getOne(accessControlQueryWrapper);

		String mess = "";
		if (accessControlServiceOne != null) {
			// 如果已存在该开门人，更新授权时间
			accessControlServiceOne.setDeadLine(alterOperatorDeadLine(time));
			boolean updateSuccess = accessControlService.update(accessControlServiceOne, accessControlQueryWrapper);

			mess = updateSuccess ? "开门人已存在，更新授权时间" : "更新失败";
		} else {
		    // 如果不存在开门人，则添加记录
			AccessControl accessControl = new AccessControl()
					.setDeviceId(deviceId)
					.setUserId(userId)
					.setDeadLine(alterOperatorDeadLine(time));

			boolean saveSuccess = accessControlService.save(accessControl);
			mess = saveSuccess ? "添加成功" : "添加失败请重新添加";
		}

		DataResponse.jsonResponse(response, mess);
	}

	/**
	 * 根据time参数返回一个localdate对象用于修改accessControl的日期
	 *
	 * @param time 授权时间
	 * @return LocalDate对象
	 */
	private LocalDate alterOperatorDeadLine(String time) {
		LocalDate deadLine = null;

		if ("1".equals(time)) {
			// 授权时间为一天
			deadLine = LocalDate.now().plusDays(1);
		} else if ("2".equals(time)) {
			// 授权时间为三天
			deadLine = LocalDate.now().plusDays(3);
		} else if ("3".equals(time)) {
			// 授权时间为三年
			deadLine = LocalDate.now().plusYears(8);
		}
		return deadLine;
	}

	/**
	 * 删除开门人
	 *
	 * @param deviceId 设备id
	 * @param userId 用户id
	 * @param response 将更新信息以json格式返回
	 */
	@PostMapping(value="/device/del/operator/{deviceId}/{userId}")
	public void delOperator(@PathVariable Integer deviceId, @PathVariable Integer userId, HttpServletResponse response) {
		QueryWrapper<AccessControl> accessControlQueryWrapper = new QueryWrapper<AccessControl>().eq(AccessControlFieldEnum.DEVICE_ID.getFieldName(), deviceId).eq(AccessControlFieldEnum.USER_ID.getFieldName(), userId);
		boolean removeSuccess = accessControlService.remove(accessControlQueryWrapper);
		String mess = removeSuccess ? "删除成功" : "删除失败";
		DataResponse.jsonResponse(response, mess);
	}
	
	
 	public class bean{
		private List<Devlogs> list=new ArrayList<>();
		private Integer resultCount;
		private Integer pageCount;
		private Integer devlogsPageNo;
		private Integer devlogsPageSize;
		public List<Devlogs> getList() {
			return list;
		}
		public void setList(List<Devlogs> list) {
			this.list = list;
		}
		public Integer getResultCount() {
			return resultCount;
		}
		public void setResultCount(Integer resultCount) {
			this.resultCount = resultCount;
		}
		public Integer getPageCount() {
			return pageCount;
		}
		public void setPageCount(Integer pageCount) {
			this.pageCount = pageCount;
		}
		public Integer getDevlogsPageNo() {
			return devlogsPageNo;
		}
		public void setDevlogsPageNo(Integer devlogsPageNo) {
			this.devlogsPageNo = devlogsPageNo;
		}
		public Integer getDevlogsPageSize() {
			return devlogsPageSize;
		}
		public void setDevlogsPageSize(Integer devlogsPageSize) {
			this.devlogsPageSize = devlogsPageSize;
		}
		
	}
 	
 	
 	/**
 	 * 同意工人发出起的对某个锁设备的临时开锁权限，默认两天
 	 * @param eventId
 	 * @param response
 	 */
 	@RequestMapping(value="/ajaxagreeapply",method=RequestMethod.POST)
 	public void agreeCasualApplyRecord(@RequestParam(value="eventId")Integer eventId,HttpServletResponse response){
 		
 		dms.modifyCasualApplyRecord(eventId, "1");
 		
 		DataResponse.jsonResponse(response, "");
 		
 	}
 	
 	
 	/**
 	 * 拒绝工人发出起的对某个锁设备的临时开锁权限，默认两天
 	 * @param eventId
 	 * @param response
 	 */
 	@RequestMapping(value="/ajaxnotagreeapply",method=RequestMethod.POST)
 	public void doNotAgreeCasualApplyRecord(@RequestParam(value="eventId")Integer eventId,HttpServletResponse response){
 		
 		dms.modifyCasualApplyRecord(eventId, "2");
 		
 		DataResponse.jsonResponse(response, "");
 		
 	}
}
